package net.guerlab.sdk.dingtalk.utils;

import net.guerlab.sdk.dingtalk.DingTalkException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 签名工具
 *
 * @author guer
 */
public class SignUtils {

    private static final String TYPE = "HmacSHA256";

    private SignUtils() {

    }

    /**
     * 签名
     *
     * @param timestamp
     *         时间戳字符串
     * @param appSecret
     *         app密钥
     * @return 签名内容
     */
    public static String sign(String timestamp, String appSecret) {
        try {
            Mac mac = Mac.getInstance(TYPE);
            mac.init(new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), TYPE));
            byte[] signatureBytes = mac.doFinal(timestamp.getBytes(StandardCharsets.UTF_8));
            return new String(Base64.encodeBase64(signatureBytes));
        } catch (Exception e) {
            throw new DingTalkException(e.getLocalizedMessage(), e);
        }
    }
}
